package com.sls.game.supply.deal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.sls.core.http.HttpClient;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.DataConversion;
import com.sls.core.util.PropertiesUtil;
import com.sls.core.util.UtilMD5Encryption;
import com.sls.game.base.module.BaseDeal;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.dao.GoodsSupplyManageDAO;
import com.sls.game.dao.maxshu.MaxshuAccountDAO;
import com.sls.game.dao.maxshu.MaxshuAsDAO;
import com.sls.game.dao.maxshu.MaxshuDAO;
import com.sls.game.dao.maxshu.MaxshuRechargeDAO;
import com.sls.game.parser.ParseMaxshuRespInfo;
import com.sls.game.pojo.GoodsManageInfo;
import com.sls.game.pojo.GoodsOrderInfo;
import com.sls.game.pojo.GoodsSupplyManageInfo;
import com.sls.game.pojo.SLSHttpInterfaceInfo;
import com.sls.game.pojo.maxshu.MaxshuAccountType;
import com.sls.game.pojo.maxshu.MaxshuAreaServer;
import com.sls.game.pojo.maxshu.MaxshuProduct;
import com.sls.game.pojo.maxshu.MaxshuRechargeType;
import com.sls.game.pojo.maxshu.MaxshuRespInfo;
import com.sls.game.service.BaseService;
@Service("maxshuTradeDeal")
public class MaxshuTradeDeal implements BaseDeal {

	@Resource(name = "maxshuAccountDAO")
	private MaxshuAccountDAO accDAO;
	@Resource(name = "maxshuRechargeDAO")
	private MaxshuRechargeDAO rechargeDAO;

	@Resource(name = "maxshuAsDAO")
	private MaxshuAsDAO asDAO;
	@Resource(name = "maxshuDAO")
	private MaxshuDAO maxshudao;

	@Resource(name = "goodsSupplyManageDAO")
	private GoodsSupplyManageDAO goodsSupplyManageDAO;

	@Resource(name = "baseServiceImp")
	private BaseService baseservice;

	public static Logger log = Logger.getLogger(MaxshuTradeDeal.class);
	private static String filename = "maxshu.properties";

	@Override
	public GoodsOrderInfo insertDealTrade(SLSHttpInterfaceInfo requestInfo,
			GoodsOrderInfo orderInfo, Head head, GoodsSupplyManageInfo goodsinfo) {

		String address = PropertiesUtil.getValue(
				"maxshu.interface.recharge.address", filename);

		String merchantId = PropertiesUtil.getValue("maxshu.merchant.id",
				filename);
		orderInfo.setRegisterAccount(merchantId);
		
		Map<String, String> map = assembleParameterOfTrade(requestInfo,
				orderInfo, goodsinfo);

		// 上游订单结果
		String orderResult = "";
		String msg = "";
		String resultOrderId = "";
		String status = "2";

		MaxshuRespInfo resInfo = sendHttpRequestOfDirectTrade(address, map,
				head);

		// 订单结果
		if (resInfo != null) {

			orderResult = resInfo.getState();
			msg = resInfo.getStateInfo();
			resultOrderId = resInfo.getMaxshuOrderId();
			if ("101".equals(orderResult)) { // 成功
				status = "1";

			} else if ("102".equals(orderResult)) { // 订单状态处理中
				status = "2";
			} else if ("103".equals(orderResult) || "901".equals(orderResult)
					|| "601".equals(orderResult)) {
				status = "3"; // 存疑
			} else {
				status = "0"; // 失败
			}
		} else {
			status = "3"; // 存疑
		}
		// 工号
//		String merchantId = orderInfo.getRegisterAccount();

		GoodsOrderInfo orderInfo_update = new GoodsOrderInfo();
		orderInfo_update.setOrderId(orderInfo.getOrderId());
		orderInfo_update.setStatus(status);// 本地对应订单状态
		orderInfo_update.setStatusRemark(msg);// 根据上游返回信息
		orderInfo_update.setSupOrderId(resultOrderId);// 上游订单号
		orderInfo_update.setRegisterAccount(merchantId);// 上游工号
		orderInfo_update.setSynOrAsy("0"); // 同步通知标识

		String supplyName = orderInfo.getSupplyName();
		int goodsCostPrice = orderInfo.getGoodsCostPrice();
		String suppliersId = orderInfo.getSupplyId();

		if (supplyName != null && !("".equals(supplyName))) {
			orderInfo_update.setSupplyName(supplyName);
		}
		if (goodsCostPrice != 0 && !("".equals(goodsCostPrice))) {
			orderInfo_update.setGoodsCostPrice(goodsCostPrice);
		}
		if (suppliersId != null && !("".equals(suppliersId))) {
			orderInfo_update.setSupplyId(suppliersId);
		}

		// 根据交易返回的结果更新订单表
		try {
			baseservice.updateOrderInfo(orderInfo_update, head);
		} catch (ServerDisponseException e) {
			log.error("请求ID：" + head.getRequestId() + "根据数网返回的结果更新订单异常！", e);
			throw e;
		} catch (Exception e) {
			log.error("请求ID：" + head.getRequestId() + "根据数网返回的结果更新订单异常！", e);
		}

		return orderInfo_update;
	}

	/**
	 * 发送供货请求
	 * */
	private MaxshuRespInfo sendHttpRequestOfDirectTrade(String url,
			Map<String, String> map, Head head) {
		MaxshuRespInfo resInfo = null;
		HttpClient httpClient = new HttpClient();

		try {
			log.info("请求ID：" + head.getRequestId() + "，发送到数网sup的直充请求参数为：" + url
					+ map);
			String xmlStr = httpClient.doPost(url, map);
			log.info("请求ID：" + head.getRequestId() + "，数网sup直充返回的结果参数为："
					+ xmlStr);
			// 对返回的xml格式字符串数据进行解析
			if (StringUtils.isNotEmpty(xmlStr)) {
				resInfo = ParseMaxshuRespInfo.getInfoOfRecharge(xmlStr);
			}
		} catch (Exception e) {
			log.error("请求ID：" + head.getRequestId() + "数网sup直充交易请求异常！", e);
		}
		return resInfo;
	}

	/**
	 * 生产请求报文
	 * */
	private Map<String, String> assembleParameterOfTrade(
			SLSHttpInterfaceInfo info, GoodsOrderInfo orderInfo,
			GoodsSupplyManageInfo goodsinfo) {

		Map<String, String> map = new HashMap<String, String>();
		String md5key = PropertiesUtil.getValue("maxshu.md5.key", filename);
		// 工号
		String merchantId = PropertiesUtil.getValue("maxshu.merchant.id",
				filename);
		String returnUrl = PropertiesUtil.getValue("maxshu.return.address",
				filename);
		


		String originalGoodsId = goodsinfo.getOriginalGoodsId();
		String orderId = orderInfo.getOrderId();
		String mechantIP = orderInfo.getMerchantIP();

		String gameArea = info.getGameArea();
		String gameServer = info.getGameServer();
		String accountTypeName = info.getAccountTypeName();
		String chargeTypeName = info.getChargeTypeName();
		String buyNum = info.getBuyNum();
		String gameAccount = info.getGameAccount();
		MaxshuAccountType account = new MaxshuAccountType();
		account.setProductId(originalGoodsId);
		account.setAccountTypeName(accountTypeName);
		List<MaxshuAccountType> accList = accDAO
				.queryByProIdAndAccountName(account);
		String game = "";
		String gameName = "";
		String targetAccountType = "";
		String targetAccountTypeName = "";
		if (accList != null && !accList.isEmpty()) {
			account = accList.get(0);
			gameName = account.getGameName();
			game = account.getGameNameValue();
			targetAccountType = account.getAccountTypeValue();
			targetAccountTypeName = account.getAccountTypeName();
		}
		MaxshuRechargeType recharge = new MaxshuRechargeType();
		recharge.setProductId(originalGoodsId);
		recharge.setRechargeTypeName(chargeTypeName);
		List<MaxshuRechargeType> rechargeList = rechargeDAO
				.queryByProIdAndRechargeName(recharge);
		String rechargeMode = "";
		String rechargeModeName = "";
		if (rechargeList != null && !rechargeList.isEmpty()) {
			recharge = rechargeList.get(0);
			gameName = recharge.getGameName();
			game = recharge.getGameNameValue();
			rechargeMode = recharge.getRechargeTypeValue();
			rechargeModeName = recharge.getRechargeTypeName();
		}
		MaxshuAreaServer as = new MaxshuAreaServer();
		as.setProductId(originalGoodsId);
		as.setAreaName(gameArea);
		as.setServerName(gameServer);
		List<MaxshuAreaServer> asList = asDAO.queryByProIdAndASName(as);
		String area = "";
		String areaName = "";
		String server = "";
		String serverName = "";
		if (asList != null && !asList.isEmpty()) {
			as = asList.get(0);
			gameName = as.getGameName();
			game = as.getGameNameValue();
			area = as.getAreaValue();
			areaName = as.getAreaName();
			server = as.getServerValue();
			serverName = as.getServerName();
		}
		String data = merchantId + orderId + originalGoodsId + buyNum
				+ gameAccount + md5key;
		String sign = UtilMD5Encryption.createMD5Encryption(data);
		map.put("MerchantID", merchantId);
		map.put("MerchantOrderID", orderId);
		map.put("ProductID", originalGoodsId);
		map.put("BuyAmount", buyNum);
		map.put("TargetAccount", gameAccount);
		if (StringUtils.isNotEmpty(targetAccountType)) {
			map.put("TargetAccountType", targetAccountType);
		}
		if (StringUtils.isNotEmpty(targetAccountTypeName)) {
			map.put("TargetAccountTypeName", targetAccountTypeName);
		}
		if (StringUtils.isNotEmpty(targetAccountType)) {
			map.put("TargetAccountType", targetAccountTypeName);
		}
		if (StringUtils.isNotEmpty(rechargeMode)) {
			map.put("RechargeMode", rechargeMode);
		}
		if (StringUtils.isNotEmpty(rechargeModeName)) {
			map.put("RechargeModeName", rechargeModeName);
		}
		if (StringUtils.isNotEmpty(game)) {
			map.put("Game", game);
		}
		if (StringUtils.isNotEmpty(gameName)) {
			map.put("GameName", gameName);
		}
		if (StringUtils.isNotEmpty(area)) {
			map.put("Area", area);
		}
		if (StringUtils.isNotEmpty(areaName)) {
			map.put("AreaName", areaName);
		}
		if (StringUtils.isNotEmpty(server)) {
			map.put("Server", server);
		}
		if (StringUtils.isNotEmpty(areaName)) {
			map.put("AreaName", areaName);
		}
		if (StringUtils.isNotEmpty(serverName)) {
			map.put("ServerName", serverName);
		}
		map.put("CustomerIP", mechantIP);
		map.put("ResponseUrl", returnUrl);
		map.put("Sign", sign);

		return map;
	}

	@Override
	public SLSHttpInterfaceInfo getGoodsDetail(
			SLSHttpInterfaceInfo sLSHttpInterfaceInfo, String originalGoodsId,
			Head head) {
		MaxshuProduct wp = this.maxshudao.queryByProId(originalGoodsId);
		List<MaxshuAreaServer> asList = this.asDAO
				.queryByProductId(originalGoodsId);
		List<String> bigAreaNameList = this.asDAO
				.queryAreaNameByProductId(originalGoodsId);
		List<String> rechargeNameList = this.rechargeDAO
				.queryRechargeNameByProductId(originalGoodsId);
		List<String> AccNameList = this.accDAO
				.queryAccNameByProductId(originalGoodsId);
		StringBuilder areaServerName = new StringBuilder();
		StringBuilder rechName = new StringBuilder();
		StringBuilder accName = new StringBuilder();
		StringBuilder sb = new StringBuilder();
		if (bigAreaNameList != null && bigAreaNameList.size() > 0) {
			for (String bigAreaName : bigAreaNameList) {
				sb.append(bigAreaName);
				sb.append("&&");
			}
		}
		if (asList != null && asList.size() > 0) {
			for (MaxshuAreaServer areaSerInfo : asList) {
				areaServerName.append(areaSerInfo.getAreaName());
				areaServerName.append("##");
				String smallServerName = areaSerInfo.getServerName();
				if (StringUtils.isNotEmpty(smallServerName)) {
					areaServerName.append(smallServerName);
				} else {
					areaServerName.append("null");
				}
				areaServerName.append("&&");
			}
		}
		if (rechargeNameList != null && rechargeNameList.size() > 0) {
			for (String reName : rechargeNameList) {
				rechName.append(reName);
				rechName.append("&&");
			}
		}
		if (AccNameList != null && AccNameList.size() > 0) {
			for (String aName : AccNameList) {
				accName.append(aName);
				accName.append("&&");
			}
		}
		String asName = areaServerName.toString();
		String areaNameStr = sb.toString();
		String rechNameStr = rechName.toString();
		String accountNameStr = accName.toString();
		String areaServer = null;
		String bigAreaName = null;
		String recharge = null;
		String account = null;
		if (asName != null && !("".equals(asName))) {
			areaServer = asName.substring(0, asName.length() - 2);
		}
		if (areaNameStr != null && !("".equals(areaNameStr))) {
			bigAreaName = areaNameStr.substring(0, areaNameStr.length() - 2);
		}
		if (rechNameStr != null && !("".equals(rechNameStr))) {
			recharge = rechNameStr.substring(0, rechNameStr.length() - 2);
		}
		if (accountNameStr != null && !("".equals(accountNameStr))) {
			account = accountNameStr.substring(0, accountNameStr.length() - 2);
		}
		StringBuilder strBui = new StringBuilder();
		strBui.append(recharge);
		strBui.append("##");
		if (wp != null) {
			String remark = wp.getRemark();
			if (StringUtils.isNotBlank(remark)) {
				strBui.append(remark);
			} else {
				strBui.append("null");
			}
		} else {
			strBui.append("null");
		}
		strBui.append("##");
		strBui.append("null");
		strBui.append("##");
		strBui.append("null");
		String chargeType = strBui.toString().trim();
		sLSHttpInterfaceInfo.setAccountType(account);
		sLSHttpInterfaceInfo.setChargeType(chargeType);
		sLSHttpInterfaceInfo.setGameServer(areaServer);
		sLSHttpInterfaceInfo.setGameArea(bigAreaName);
		sLSHttpInterfaceInfo.setGameUnit("元");
		return sLSHttpInterfaceInfo;
	}

	@Override
	public void addGoodsSupplyRelation(GoodsSupplyManageInfo supplyinfo,
			GoodsSupplyManageInfo beforeaddInfo) {
		// TODO Auto-generated method stub
		// 供应商编号
		String supplyId = supplyinfo.getSuppliersId();
		// 原始商品编号
		String originalGoodsId = supplyinfo.getOriginalGoodsId();
		beforeaddInfo.setSuppliersId(supplyId);
		beforeaddInfo.setSupplyName("数网");
		MaxshuProduct wInfo = this.maxshudao.queryByProId(originalGoodsId);
		if (wInfo != null) {
			// 进价
			String unitPrice = wInfo.getProductPrice();
			int goodsCostPrice = DataConversion.toInt(unitPrice);
			beforeaddInfo.setGoodsCostPrice(goodsCostPrice);
			// 商品面值
			String parValue = wInfo.getProductParvalue();
			int goodsValue = DataConversion.toInt(parValue);

			beforeaddInfo.setGoodsValue(goodsValue);
			beforeaddInfo.setRemark("数网商品供应新增");
			try {
				goodsSupplyManageDAO.insert(beforeaddInfo);
			} catch (Exception e) {
				log.error("数网商品供应新增时出现异常", e);
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		} else {
			throw new ServerDisponseException(
					ExceptionCodeDes.ORIGINAL_GOODS_NOT_EXTIS.getCode(),
					ExceptionCodeDes.ORIGINAL_GOODS_NOT_EXTIS.getDescription());
		}
	}

	@Override
	public GoodsSupplyManageInfo querySupplyprice(String originalGoodsId) {
		// TODO Auto-generated method stub
		MaxshuProduct wp = this.maxshudao.queryByProId(originalGoodsId);
		GoodsSupplyManageInfo returninfo = new GoodsSupplyManageInfo();
		if (wp != null) {
			returninfo.setGoodsCostPrice(DataConversion.toInt(wp
					.getProductPrice()));
			returninfo.setGoodsValue(DataConversion.toInt(wp
					.getProductParvalue()));
		}
		return returninfo;
	}
	
	@Override
	public GoodsManageInfo getProductFromProduct(String originalGoodsId,
			GoodsManageInfo goodsManageInfo1, Head head) {
		// TODO Auto-generated method stub
		String goodsName = "";
		MaxshuProduct wogreat = this.maxshudao.queryByProId(originalGoodsId);
		if (wogreat != null) {
			// 商品名称
			goodsName = wogreat.getProductName();
			// 商品面值
			String parValueOri = wogreat.getProductParvalue();
			int parValue = DataConversion.toInt(parValueOri); // 单位转换为厘
			String inPrice = wogreat.getProductPrice();
			int inPrice2 = DataConversion.toInt(inPrice);
			// 官方网址
			String officialUrl = "";
			// 充值方式
			String rechargeMode = "";
			String type = wogreat.getRechargeMode();
			if ("2".equals(type)) {
				rechargeMode = "2";
			} else {
				rechargeMode = "1";
			}

			goodsManageInfo1.setGoodsMoney(parValue);
			goodsManageInfo1.setCommonSalePrice(inPrice2);
			goodsManageInfo1.setOfficialUrl(officialUrl);
			goodsManageInfo1.setRechargeMode(rechargeMode);
			goodsManageInfo1.setGoodsName(goodsName);
		} else {
			log.error("原始商品不存在！");
			throw new ServerDisponseException(
					ExceptionCodeDes.ORIGINAL_GOODS_NOT_EXTIS.getCode(),
					ExceptionCodeDes.ORIGINAL_GOODS_NOT_EXTIS.getDescription());
		}

		return goodsManageInfo1;
	}

	public MaxshuAccountDAO getAccDAO() {
		return accDAO;
	}

	public void setAccDAO(MaxshuAccountDAO accDAO) {
		this.accDAO = accDAO;
	}

	public MaxshuRechargeDAO getRechargeDAO() {
		return rechargeDAO;
	}

	public void setRechargeDAO(MaxshuRechargeDAO rechargeDAO) {
		this.rechargeDAO = rechargeDAO;
	}

	public MaxshuAsDAO getAsDAO() {
		return asDAO;
	}

	public void setAsDAO(MaxshuAsDAO asDAO) {
		this.asDAO = asDAO;
	}

	public BaseService getBaseservice() {
		return baseservice;
	}

	public void setBaseservice(BaseService baseservice) {
		this.baseservice = baseservice;
	}

	public MaxshuDAO getMaxshudao() {
		return maxshudao;
	}

	public void setMaxshudao(MaxshuDAO maxshudao) {
		this.maxshudao = maxshudao;
	}

	public GoodsSupplyManageDAO getGoodsSupplyManageDAO() {
		return goodsSupplyManageDAO;
	}

	public void setGoodsSupplyManageDAO(
			GoodsSupplyManageDAO goodsSupplyManageDAO) {
		this.goodsSupplyManageDAO = goodsSupplyManageDAO;
	}



}
